package com.tanhua.server.server;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLocation;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {
@DubboReference
private RecommendUserApi recommendUserApi;
@DubboReference
private UserInfoApi userInfoApi;
@DubboReference
private QuestionApi questionApi;
@Autowired
private HuanXinTemplate huanXinTemplate;
@DubboReference
private UserLocationApi userLocationApi;
//今日最佳
    public TodayBest todayBest() {
        Long toUserId = UserHolder.getUserId();
        //调api根据touserid查缘分值和用户信息
       RecommendUser  recommendUser =  recommendUserApi.todayBest(toUserId);
       //获取缘分值最高用户id
        Long userId = recommendUser.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);
        //转化为todaybest
        TodayBest todayBest = new TodayBest();
        BeanUtils.copyProperties(userInfo,todayBest);
        todayBest.setFateValue(recommendUser.getScore().longValue());
        //其他转化tags类型不同，userInfo是string类型  返回数组类型,转化为数组
        todayBest.setTags(userInfo.getTags().split(","));
        return todayBest;
    }
    //查询首页推荐佳人数据
    public PageResult recommendation(Integer page, Integer pageSize) {
        Long userId = UserHolder.getUserId();
        List<RecommendUser> recommendUserList = recommendUserApi.pageList(userId,page,pageSize);
        if(CollectionUtil.isEmpty(recommendUserList)){
           recommendUserList = defaultList();
        }
        //最终要得到vo列表
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            UserInfo info = userInfoApi.findById(recommendUser.getUserId());
            //todaybest的赋值工具类
            TodayBest vo = TodayBest.init(info, recommendUser);
            vos.add(vo);
        }
        //构建返回值pageResult对象

        return new PageResult(page,pageSize,0l,vos);
    }
    //企业构造默认推荐佳人数据的方法
    private List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        //构造默认推荐数据，企业中按照项目经理要求
        for (int i = 1; i <= 10; i++) {
            RecommendUser ru = new RecommendUser();
            ru.setUserId((long) i); //模拟推荐的用户id
            ru.setScore(95D); //模拟推荐的评分
            list.add(ru);
        }
        return list;
    }
    //查询佳人详细信息
    public TodayBest personalInfo(Long id) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看传入用户的详细信息，
        UserInfo info = userInfoApi.findById(id);
        //查询推荐数据
       RecommendUser user = recommendUserApi.selectByUserId(id,userId);
        // 并构建todaybest对象返回
       return TodayBest.init(info,user);

    }

    public String strangerQuestions(Long userId) {
        Question question = questionApi.fingByUser(userId);

        //陌生人问题如果为空，则设置默认问题
        //如果questin对象为空，不能在外边getTxt，否则会空指针异常，要三元判断非空在获取
        return question==null?"你喜欢java吗":question.getTxt();
    }
//回复陌生人问题
    public void replyQuestion(Long userId,String reply) {

        //通过环信给用户发送回复
         //环信账号,构建回复内容，json串环信支持发送
        String hx="hx"+userId;
        Map map = new HashMap<>();
        map.put("userId",UserHolder.getUserId());   //发送人的id
        map.put("huanXinId","hx"+UserHolder.getUserId());  //发送人的环信id
        UserInfo info = userInfoApi.findById(UserHolder.getUserId());
        map.put("nickname",info.getNickname()); //发送人的昵称
        map.put("strangerQuestion",strangerQuestions(userId));  //发送人的昵称
        map.put("reply",reply);
        //发布的消息json串，，只有按照该格式发送，客户端才能解析
        String message = JSON.toJSONString(map);
        huanXinTemplate.sendMsg(hx,message); //环信账号，发布的json串

    }
  //搜附近
    public List<NearUserVo> search(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        //调api查询附近的地理位置，返回附近人的用户id集合
        List<Long> list = userLocationApi.findNear(userId,distance);
        //查询附近人的用户信息
        Map<Long, UserInfo> map = userInfoApi.findIds(list);
        //构建vo对象返回，
        ArrayList<NearUserVo> vos = new ArrayList<>();
        for (Long id : list) {
            if(id==userId){  //不显示自己在地图的位置
                continue;
            }
            UserInfo userInfo = map.get(id);
            if(!userInfo.getGender().equals(gender)){//根据性别筛选
                continue;
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            vos.add(vo);
        }
        return vos;
    }
}
